package com.xmxsuperstar.app;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.URL;
import java.util.Date;
import java.util.Scanner;

import net.love5z.common.codec.Base64;
import net.love5z.common.utils.URLUtils;

public class SocketClient {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Scanner consoleIn = new Scanner(new InputStreamReader(System.in));
		System.out.print("Server Name: ");
		String srv = consoleIn.nextLine();
		while (true) {
			try {
				System.out.print("Request Url: ");
				String urlString = consoleIn.nextLine();

				URL url = new URL(urlString);

				Socket socket = new Socket(srv, 10000);
				BufferedReader in = new BufferedReader(new InputStreamReader(
						socket.getInputStream()));
				PrintWriter out = new PrintWriter(socket.getOutputStream(),
						true);

				StringBuilder request = new StringBuilder();
				StringBuilder httpRequest = new StringBuilder();

				httpRequest.append(
						"GET " + URLUtils.getRequestPath(url) + " HTTP/1.1")
						.append(CommonConstants.CRLF);
				httpRequest.append("Host: " + URLUtils.getHostFromUrl(url))
						.append(CommonConstants.CRLF);
				httpRequest
						.append("User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1")
						.append(CommonConstants.CRLF);
				httpRequest.append("Accept-Language: en-us,en;q=0.5").append(
						CommonConstants.CRLF);
				// httpRequest.append("Accept-Encoding: gzip, deflate").append(
				// Constants.CRLF);
				httpRequest.append("Accept-Encoding: deflate").append(
						CommonConstants.CRLF);

				// httpRequest.append("Keep-Alive: 5").append(Constants.CRLF);
				// httpRequest.append("Connection: keep-alive").append(
				// Constants.CRLF);

				httpRequest.append("Connection: close").append(CommonConstants.CRLF);

				httpRequest.append(CommonConstants.CRLF);

				request.append("GET")
						.append("\n")
						.append(urlString)
						.append("\n")
						.append(Base64.encode(httpRequest.toString().getBytes(
								CommonConstants.CHAR_ENCODING))).append("\n");

				out.write(Base64.encode(request.toString().getBytes("UTF-8"))
						+ "\n");

				out.flush();

				Date begin = new Date();

				String line = in.readLine();

				Date end = new Date();

				System.out.println("Response Content: ");
				System.out.println(new String(Base64.decode(line),
						CommonConstants.CHAR_ENCODING));

				System.out.println("Request time: "
						+ (end.getTime() - begin.getTime()) / 1000);

				out.close();
				in.close();
				socket.close();
			} catch (IOException e) {
			}
		}

	}
}
